import 'dart:convert';
import 'package:grint/entity/chat_message.dart';
import 'package:grint/utils/local_store.dart';

/// 聊天数据管理类
class ChatData {
  static final ChatData _instance = ChatData._internal();
  factory ChatData() => _instance;
  ChatData._internal();

  final LocalStore _localStore = LocalStore();

  /// 获取用户的所有会话
  Future<List<ChatConversation>> getUserConversations(String userId) async {
    final conversationsJson = _localStore.getTextValue(
      'conversations_$userId',
      defaultValue: '[]',
    );

    final List<dynamic> conversationsList = jsonDecode(conversationsJson);
    return conversationsList
        .map((json) => ChatConversation.fromJson(json))
        .toList()
      ..sort((a, b) => b.lastActiveAt.compareTo(a.lastActiveAt));
  }

  /// 获取两个用户之间的会话
  Future<ChatConversation?> getConversationBetweenUsers(
    String userId1,
    String userId2,
  ) async {
    final conversations1 = await getUserConversations(userId1);

    for (final conversation in conversations1) {
      if (conversation.containsUser(userId2)) {
        return conversation;
      }
    }

    return null;
  }

  /// 创建新会话
  Future<ChatConversation> createConversation(
    String userId1,
    String userId2,
  ) async {
    final conversationId = 'conv_${DateTime.now().millisecondsSinceEpoch}';
    final conversation = ChatConversation(
      id: conversationId,
      userId1: userId1,
      userId2: userId2,
      lastActiveAt: DateTime.now(),
    );

    // 保存到两个用户的会话列表中
    await _saveConversationForUser(userId1, conversation);
    await _saveConversationForUser(userId2, conversation);

    return conversation;
  }

  /// 为用户保存会话
  Future<void> _saveConversationForUser(
    String userId,
    ChatConversation conversation,
  ) async {
    final conversations = await getUserConversations(userId);

    // 检查是否已存在
    final existingIndex = conversations.indexWhere(
      (c) => c.id == conversation.id,
    );
    if (existingIndex != -1) {
      conversations[existingIndex] = conversation;
    } else {
      conversations.add(conversation);
    }

    final conversationsJson = jsonEncode(
      conversations.map((c) => c.toJson()).toList(),
    );
    await _localStore.setTextValue('conversations_$userId', conversationsJson);
  }

  /// 获取会话中的消息
  Future<List<ChatMessage>> getConversationMessages(
    String conversationId,
  ) async {
    final messagesJson = _localStore.getTextValue(
      'messages_$conversationId',
      defaultValue: '[]',
    );

    final List<dynamic> messagesList = jsonDecode(messagesJson);
    return messagesList.map((json) => ChatMessage.fromJson(json)).toList()
      ..sort((a, b) => a.createdAt.compareTo(b.createdAt));
  }

  /// 发送消息
  Future<ChatMessage> sendMessage({
    required String conversationId,
    required String senderId,
    required String receiverId,
    required String content,
    required MessageType type,
  }) async {
    final messageId = 'msg_${DateTime.now().millisecondsSinceEpoch}';
    final message = ChatMessage(
      id: messageId,
      senderId: senderId,
      receiverId: receiverId,
      content: content,
      type: type,
      createdAt: DateTime.now(),
    );

    // 保存消息
    await _saveMessage(conversationId, message);

    // 更新会话信息
    await _updateConversationLastMessage(conversationId, message);

    return message;
  }

  /// 保存消息
  Future<void> _saveMessage(String conversationId, ChatMessage message) async {
    final messages = await getConversationMessages(conversationId);
    messages.add(message);

    final messagesJson = jsonEncode(messages.map((m) => m.toJson()).toList());
    await _localStore.setTextValue('messages_$conversationId', messagesJson);
  }

  /// 更新会话的最后消息
  Future<void> _updateConversationLastMessage(
    String conversationId,
    ChatMessage message,
  ) async {
    // 获取会话信息
    final conversation = await _getConversationById(conversationId);
    if (conversation == null) return;

    // 更新会话
    final updatedConversation = conversation.copyWith(
      lastMessageId: message.id,
      lastActiveAt: message.createdAt,
      // 未读计数逻辑可以在后续优化
      unreadCount: conversation.unreadCount,
    );

    // 保存到两个用户的会话列表
    await _saveConversationForUser(conversation.userId1, updatedConversation);
    await _saveConversationForUser(conversation.userId2, updatedConversation);
  }

  /// 根据ID获取会话
  Future<ChatConversation?> _getConversationById(String conversationId) async {
    // 这里简化处理，实际应该有更好的索引方式
    final allUsers = [
      '1001',
      '1002',
      '1003',
      '1004',
      '1005',
      '1006',
      '1007',
      '1008',
    ];

    for (final userId in allUsers) {
      final conversations = await getUserConversations(userId);
      final conversation =
          conversations.where((c) => c.id == conversationId).firstOrNull;
      if (conversation != null) {
        return conversation;
      }
    }

    return null;
  }

  /// 标记消息为已读
  Future<void> markMessagesAsRead(String conversationId, String userId) async {
    final messages = await getConversationMessages(conversationId);
    bool hasUpdates = false;

    final updatedMessages =
        messages.map((message) {
          if (message.receiverId == userId && !message.isRead) {
            hasUpdates = true;
            return message.copyWith(isRead: true);
          }
          return message;
        }).toList();

    if (hasUpdates) {
      final messagesJson = jsonEncode(
        updatedMessages.map((m) => m.toJson()).toList(),
      );
      await _localStore.setTextValue('messages_$conversationId', messagesJson);

      // 重置未读计数
      await _resetUnreadCount(conversationId, userId);
    }
  }

  /// 重置未读计数
  Future<void> _resetUnreadCount(String conversationId, String userId) async {
    final conversation = await _getConversationById(conversationId);
    if (conversation == null) return;

    final updatedConversation = conversation.copyWith(unreadCount: 0);
    await _saveConversationForUser(userId, updatedConversation);
  }

  /// 删除会话
  Future<void> deleteConversation(String conversationId, String userId) async {
    final conversations = await getUserConversations(userId);
    conversations.removeWhere((c) => c.id == conversationId);

    final conversationsJson = jsonEncode(
      conversations.map((c) => c.toJson()).toList(),
    );
    await _localStore.setTextValue('conversations_$userId', conversationsJson);
  }

  /// 获取最后一条消息
  Future<ChatMessage?> getLastMessage(String conversationId) async {
    final messages = await getConversationMessages(conversationId);
    return messages.isNotEmpty ? messages.last : null;
  }
}
